/**
 * Created by hzw on 2016/4/15.
 * connect 342782880
 * @params url 数据请求地址
 * @params keyName 数据返回的列表字段
 * @params datafilter 数据过滤函数，过程写在datafilter.js
 * @params headName,表格的标题栏
 * @params param,数据需要显示的字段
 */

import React from "react"
var  DataFilter=require("../js/datafilter");
import UNIT from '../js/unit'
var Tdcontent=React.createClass({
    render: function() {
        var list=this.props.params.split(",");
        var data=this.props.data;
        var Nodes = list.map(function (comment) {
            return (
                <td>{data[comment]}</td>
            )
        });
        return (
            <tr>
            {Nodes}
            </tr>
        );
    }
})

var Tbody = React.createClass({
    render: function() {
        var list=this.props.params;
        var Nodes = this.props.data.map(function (comment) {
                return (
                    <Tdcontent data={comment} params={list}/>
                )
        });
        return (
            <tbody>
                {Nodes}
            </tbody>
        );
    }
});
var Thead = React.createClass({
    render: function() {
        var list=this.props.headName.split(",");
        var Nodes = list.map(function (comment) {
            return (
                    <th>{comment}</th>
            );
        });
        return (
            <thead>
                <tr>
                {Nodes}
                </tr>
            </thead>
        );
    }
});
var table = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    loadDate:function(){
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            cache: false,
            success: function(data){
                if(this.props.datafilter){
                    eval("DataFilter."+this.props.datafilter+"(data)");
                }
                this.setState({data: data[this.props.keyName]});
                UNIT.loadingClose();
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
                UNIT.loadingClose();
            }.bind(this)
        });
    },
    componentDidMount:function(){
        this.loadDate();
    },
    render: function() {
        return (
            <table className="table table-striped">
                <Thead headName={this.props.headName} />
                <Tbody data={this.state.data} params={this.props.params} />
            </table>
        );
    }
})

module.exports=table;